package com.kedacom.demo.springrabbit.test;

import java.io.UnsupportedEncodingException;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class RPCClient {

	private static Logger logger = LoggerFactory.getLogger(RPCClient.class);

	public static void main(String[] args) throws InterruptedException, UnsupportedEncodingException {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"/springrabbit/test/spring-rabbitmq-rpc-client.xml");
		RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);

		Object requestObject = new Message("test message");
		String jsonString = JSONObject.fromObject(requestObject).toString();
		byte[] bytes = (byte[]) rabbitTemplate.convertSendAndReceive(jsonString);
		String result = new String(bytes, "utf8");
		logger.debug("receive response {}", result);

		jsonString = JSONObject.fromObject(new Message("test message 2")).toString();
		org.springframework.amqp.core.Message res = rabbitTemplate
				.sendAndReceive(new org.springframework.amqp.core.Message(jsonString.getBytes(),
						new MessageProperties()));
		logger.debug("receive response {}", new String(res.getBody()));
	}

}
